<?php

namespace App\Http\Controllers\Component;

use App\Http\Controllers\CommonController;
use App\Models\Member;
use App\Services\Service\Helper;
use Illuminate\Http\Request;
use Numa\Aodao\Facade;
use Numa\Aodao\NumaException;

class SmsController extends CommonController
{
    /**
     * 短信验证码发送
     *
     * @param Request $request
     */
    public function mobile(Request $request)
    {
        if ($request->ajax()) {
            $verycode = $request->input('verify', '');
            $mobile = $request->input('mobile', '');
            $type = $request->input('type', 'reg');
            if (!Helper::checkMobileValid($mobile)) {
                return $this->error('手机号码格式错误');
            }
            if (!in_array($type, array('reg', 'forgot'))) {
                return $this->error('业务类型有误');
            }
            //验证图形码是否正确
            if (!captcha_check($verycode)) {
                return $this->error('图形验证码无效');
            }
            $member = Member::where('mobile', $mobile)->first();
            if ($type == 'reg') {
                if (!is_null($member)) {
                    return $this->error('手机号已被注册');
                }
            } elseif ($type == 'forgot') {
                if (is_null($member)) {
                    return $this->error('手机号尚未注册');
                }
            }
            //发送验证码
            try {
                $sms = Facade::sms();
                $mins = env('NUMA_AODAO_CODE_EXPIRE', 5);
                if ($type == 'reg') {
                    $content = '验证码${code},欢迎您注册驽马小程序平台,' . $mins . '分钟内有效【驽马小程序】';
                } elseif ($type == 'forgot') {
                    $content = '验证码${code},正在操作找回密码，如非本人操作请忽略,' . $mins . '分钟内有效【驽马小程序】';
                }
                $result = $sms->code($mobile, $content);
                if ($result['error']) {
                    return $this->error($result['message']);
                }
                return $this->success('success');
            } catch (NumaException $e) {
                $error = $e->toArray();
                return $this->error($error['message']);
            }
        }
    }
}
